package com.ljf.tijian.AI;

import com.ljf.tijian.AI.aiservice.KimiAiServiceImpl;
import com.ljf.tijian.pojo.AI.Message;
import com.ljf.tijian.pojo.AI.KimiRequest;
import com.ljf.tijian.pojo.AI.KimiResponse;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

@Service
@ConfigurationProperties(prefix = "kimi")
public class KimiAiService implements KimiAiServiceImpl {
    private String url;
    private String key;

    public void setUrl(String url) {
        this.url = url;
    }

    public void setKey(String key) {
        this.key = key;
    }

    @Override
    public String call(String message) {
//        System.out.println("Kimi URL: " + url);  // 检查URL是否正确
//        System.out.println("Kimi Key: " + key);  // 检查Key是否正确

        //构建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        headers.add("Accept", "application/json");
        headers.add("Authorization", "Bearer "+key);
        //构建请求体
        KimiRequest zhipuRequest = new KimiRequest();
        zhipuRequest.setModel("moonshot-v1-8k");
        Message msg = new Message();
        msg.setRole("user");
        msg.setContent(message);
        List<Message> messageArrayList = new ArrayList<>();
        messageArrayList.add(msg);
        zhipuRequest.setMessages(messageArrayList);
        //拼接请求头和请求体
        HttpEntity<KimiRequest> httpEntity = new HttpEntity<>(zhipuRequest,headers);
        //发送请求接受响应
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<KimiResponse> response = restTemplate.exchange(url, HttpMethod.POST, httpEntity, KimiResponse.class);
        return response.getBody().getChoices().get(0).getMessage().getContent();
    }
}
